/**
 * Holyset Ltd Co.
 */
package com.hs.gas.client;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author <a href="mailto:guangzong@gmail.com">Guangzong Syu</a>
 *
 */
public class Test2 implements SerialPortEventListener {

	private InputStream is;
	public static void main(String[] args) throws Exception {
		CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM9");
		SerialPort serialPort = (SerialPort) portIdentifier.open("timer", 2000);
		serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
				SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
		serialPort.notifyOnDataAvailable(true);
		serialPort.setOutputBufferSize(8);
		InputStream is = serialPort.getInputStream();
		Test2 t = new Test2(is);
		serialPort.addEventListener(t);
	}

	public Test2(InputStream is) {
		this.is = is;
	}

	/* (non-Javadoc)
	 * @see gnu.io.SerialPortEventListener#serialEvent(gnu.io.SerialPortEvent)
	 */
	public void serialEvent(SerialPortEvent event) {
		if( SerialPortEvent.DATA_AVAILABLE == event.getEventType()) {
			int[] dataes = new int[8];
			try {
				int data = -1;
				int i = 0;
				while((data = is.read()) != -1) {
					if(i <= 8) {
						dataes[i] = data;
					}
					i++;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			long l = 0;
			for(int i = 3; i < 7; i++) {
				l = (l * 256) + dataes[i];
			}
			System.out.println(l);
		}
	}
}
